﻿using System;
using System.Collections.ObjectModel;
using MvvmFx.Common.ViewModels;

namespace MvvmFx.Samples.HowTos.PropertyHandlers.ViewModels
{
    public class NumberChangeLogViewModel : ViewModelBase
    {
        public NumberChangeLogViewModel(NumberViewModel number)
        {
            _number = number;
            this.ChangeLog = new ObservableCollection<string>();

            //_number.AddHandler("Value", OnValueChanged);
            //_number.AddHandler("IsNegative", OnIsNegativeChanged);
            //_number.AddHandler("IsEven", OnIsEvenChanged);

            _number.NewPropertyObserver()
                .AddHandler("Value", n => Log("Value: " + n.Value))
                .AddHandler("IsNegative", this.AppendIsNegative)
                .AddHandler("IsEven", this.AppendIsEven);
        }

        void AppendIsNegative(NumberViewModel number)
        {
            if (number.IsNegative)
                this.Log("\tNumber is now negative");
            else
                this.Log("\tNumber is now positive");
        }

        void AppendIsEven(NumberViewModel number)
        {
            if (number.IsEven)
                this.Log("\tNumber is now even");
            else
                this.Log("\tNumber is now odd");
        }

        void Log(string message)
        {
            this.ChangeLog.Add(message);
            this.OnLogged();
        }

        public ObservableCollection<string> ChangeLog { get; private set; }

        private NumberViewModel _number;

        /// <summary>
        /// Gets or sets the value of the <see cref=”Number”/> property.
        /// </summary>
        public NumberViewModel Number
        {
            get { return _number; }
            set
            {
                if (_number != value)
                {
                    _number = value;
                    OnPropertyChanged("Number");
                }
            }
        }

        #region Logged Event

        public event EventHandler Logged;

        void OnLogged()
        {
            EventHandler handler = this.Logged;
            if (handler != null)
                handler(this, EventArgs.Empty);
        }

        #endregion // Logged Event
    }
}